package com.itheima.controller;

import ch.qos.logback.core.util.FileUtil;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${srcSave}")
    private String src;
    @PostMapping("/upload")
    public R con(MultipartFile file) throws IOException {
        //获取当前图片的原始name
        String filename = file.getOriginalFilename();

        String name = FilenameUtils.getExtension(filename);

        UUID uuid = UUID.randomUUID();
        String id = uuid+"."+name;
        //通过IO流将其写入磁盘
        file.transferTo(new File(src+id));
        //响应
        return R.success(id);
    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws Exception {
        //通过IO流将传过来的图片id在磁盘中读取
        FileInputStream inputStream = new FileInputStream(new File(src+ name));

        try {
            //拷贝到浏览器上
            IOUtils.copy(inputStream,response.getOutputStream());
        } finally {
            inputStream.close();
        }



    }


}
